package app.controllers;

import app.models.Convenio;
import app.services.ConvenioService;
import app.services.LogService;
import app.util.Constants;
import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.Validator;

@Resource
public class ConvenioController extends Controller{

	private final Result result;
	private final ConvenioService service;
	private final Validator validator;
	private final LogService logService;
	
	public ConvenioController(Result result, Validator validator, ConvenioService service, LogService logService) {
		
		this.result = result;
		this.service = service;
		this.validator = validator;
		this.logService = logService;
	}
	
	@Get("/convenios")
	public void index() {
		result.include("convenioList", service.findAll());
		result.include("lastConvenioList", service.findLastConvenios());
	}

	@Get("/convenios/new")
	public void form() {}
	
	@Post("/convenios/save")
	public void create(Convenio convenio) {
		
		validator.validate(convenio);
		
		validator.onErrorForwardTo(this).form();
		service.create(convenio);
		
		logService.createLog(Constants.NEW_CONVENIO + convenio.getId());
		
		result.forwardTo(this).index();
	}
	
	@Get("/convenios/{id}/edit")
	public void edit(Long id) {
		result.include("convenio", service.find(id));
	}
	
	@Post("/convenios/update")
	public void update(Convenio convenio) {
		
		validator.validate(convenio);
		
		validator.onErrorForwardTo(this).edit(convenio.getId());
		service.update(convenio);
		
		logService.createLog(Constants.UPDATE_CONVENIO + convenio.getId());
		
		result.forwardTo(this).index();
	}
	
}